package com.feifan.exception;

import com.feifan.service.JsonResult;
import com.feifan.service.ResultObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常类
 *
 * @author Donald
 * @create 2019-03-22 0:05
 */
@ControllerAdvice
public class GolableException {

    private static final Logger LOGGER = LoggerFactory.getLogger(GolableException.class);

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public JsonResult getMyException(Exception e) {
        LOGGER.error(String.format("运行时异常：：[%s]", e.getMessage()),e);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMessage(e.getMessage());
        return jsonResult;
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object getExecption(Exception e) {
        LOGGER.error(String.format("全局异常[%s]", e.getMessage()), e);
        return new JsonResult("全局异常");
    }

    /**
     * shiro 认证异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ShiroException.class)
    public ResultObject throwShiroExce(ShiroException e) {
        Subject subject = SecurityUtils.getSubject();
        String username = (String)subject.getPrincipal();
        LOGGER.info("{} 用户访问失败，权限不够，{},请练习管理员申请对应的权限", username, e.getMessage(), e);
        return ResultObject.build(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(UnauthenticatedException.class)
    public ResultObject throwUnAnon(UnauthenticatedException e) {
        LOGGER.info("本方法不允许匿名访问:", e);
        return ResultObject.build("本方法不支持匿名访问，请先登录");
    }

}
